/**
 * 
 */
package com.effectivsocial.email;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.scheduling.annotation.Async;
import org.thymeleaf.TemplateEngine;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Dhrubo
 *
 */
@Named
@Slf4j
public class EmailOperationTemplate {
	
	@Inject
	private SmtpServer smtpServer;
	
	@Inject
	private TemplateEngine templateEngine;
	
	@Async
	public void send(Email email){
		SendMailSession session = smtpServer.createSession();
		session.open();
		log.info("Sending email started.");
		session.sendMail(email);
		log.info("Send email.");
		session.close();
		log.info("End email session.");
	}
	
	
	@Async
	public void send(Email email, EmailBodyPreparer<?> emailBodyPreparer){
		
		email.addHtml(emailBodyPreparer.prepareFromTemplate(templateEngine), "UTF-8");
		send(email);
	}
	
	@Async
	public void send(List<Email> emails){
		SendMailSession session = smtpServer.createSession();
		session.open();
		
		for(Email email : emails) {
			session.sendMail(email);
		}
				
		session.close();
	}
	
}
